#include "inventorydao.h"

InventoryDAO::InventoryDAO(Database *db) : m_db(db) {}

int InventoryDAO::getCurrentStock(int productId)
{
    QString query = "SELECT current_stock FROM inventory WHERE product_id = ?";
    QVector<QMap<QString, QVariant>> result = m_db->query(query, {productId});

    if (result.isEmpty()) {
        return 0;
    }

    return result.first()["current_stock"].toInt();
}

/**
 * 库存扣减算法
 * 业务逻辑：安全地扣减商品库存，防止库存变为负数
 * 扣减机制：
 * 1. 使用原子性UPDATE操作确保并发安全
 * 2. 通过WHERE条件检查当前库存是否足够
 * 3. 只有当前库存>=扣减数量时才执行扣减
 * 4. 如果库存不足，操作失败，保护数据完整性
 * 
 * @param productId 商品ID
 * @param quantity 扣减数量
 * @return 扣减是否成功
 */
bool InventoryDAO::decreaseStock(int productId, int quantity)
{
    QString query = "UPDATE inventory SET current_stock = current_stock - ? WHERE product_id = ? AND current_stock >= ?";
    return m_db->execute(query, {quantity, productId, quantity});
}

/**
 * 库存增加算法
 * 业务逻辑：增加商品库存数量，用于入库、退货等场景
 * 增加机制：
 * 1. 直接在当前库存基础上增加指定数量
 * 2. 使用原子性UPDATE操作确保数据一致性
 * 3. 适用于商品入库、订单取消库存恢复等场景
 * 
 * @param productId 商品ID
 * @param quantity 增加数量
 * @return 增加是否成功
 */
bool InventoryDAO::increaseStock(int productId, int quantity)
{
    QString query = "UPDATE inventory SET current_stock = current_stock + ? WHERE product_id = ?";
    return m_db->execute(query, {quantity, productId});
}

bool InventoryDAO::updateSafetyStock(int productId, int safetyStock)
{
    QString query = "UPDATE inventory SET safety_stock = ? WHERE product_id = ?";
    return m_db->execute(query, {safetyStock, productId});
}

QVector<QMap<QString, QVariant>> InventoryDAO::getLowStockProducts()
{
    QString query = "SELECT p.product_id, p.product_name, i.current_stock, i.safety_stock "
                   "FROM inventory i "
                   "JOIN product p ON i.product_id = p.product_id "
                   "WHERE i.current_stock <= i.safety_stock";
    return m_db->query(query);
}
